<?php

namespace admin\components;

use app\components\BaseController;
use app\models\Admin;
use app\models\AdminMenu;
use yii;
use yii\base\View;
use yii\base\ViewEvent;
use yii\filters\AccessControl;
use yii\helpers\Url;

class BaseAuthController extends BaseController {

    public $name = '';
    /**
     * @var Admin
     */
    public $user;

    public function beforeAction($action) {
        $this->user = Yii::$app->user->identity;
        Yii::$app->view->on(View::EVENT_BEFORE_RENDER, [$this, 'beforeRender'], NULL, FALSE);
        if (empty($this->view->title)) {
            $this->view->title = $this->name;
        }
        return parent::beforeAction($action);
    }

    public function afterAction($action, $result) {
        $result = parent::afterAction($action, $result);
        if (is_array($result) && isset($result['code']) && $result['code'] == 0) {
            if (empty($result['redirect'])) {
                $url = Yii::$app->request->referrer;
                if (NULL === $url) {
                    $url = Url::to(["{$this->id}/"]);
                }
                $result['redirect'] = $url;
            }
        }
        return $result;
    }

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    ['actions' => ['login'], 'allow' => TRUE, 'roles' => ['?']],
                    ['actions' => ['error'], 'allow' => TRUE, 'roles' => ['@']],
                    ['allow' => TRUE, 'roles' => ['@'], 'matchCallback' => function () {
                        return $this->checkAccess();
                    },
                        'denyCallback' => function () {
                            echo Yii::t('yii', 'You are not allowed to perform this action.');
                            if (Yii::$app->user->isGuest) {
                                Yii::$app->user->loginRequired();
                            } else {
                                $uid = Yii::$app->user->id;
                                Yii::warning("用户ID:{$uid} 非法访问: {$this->id}/", 'admin');
                            }
                        }
                    ],
                ],

            ],
//            'log' => [
//                'class' => AdminLogControl::className()
//            ]
        ];
    }

    public function checkAccess() {
        if (Admin::loginUserIsRoot() || $this->action->id == 'logout') {
            return TRUE;
        }

        $id = $this->id;
        $actionId = $this->action->id;
        $uid = intval($this->get('id'));
        if ($id == 'user' && $actionId == 'save') {
            if (Yii::$app->user->id === $uid) {
                return TRUE;
            }
            if ($uid === 1) {
                return FALSE;
            }
        }
        return $this->checkAccessByGroup();
    }

    public function checkAccessByGroup($redirect = TRUE) {
        $model = new AdminMenu();
        $menus = $model->getUserMenus();
        if (empty($menus)) {
            return FALSE;
        }

        $id = $this->id;
        $menus[] = ['url' => 'upload/'];
        foreach ($menus as $menu) {
            if (strpos($menu['url'], $id) !== FALSE) {
                return TRUE;
            }
        }
        if ($id == Yii::$app->defaultRoute && $redirect) {
            $menu = reset($menus);
            $this->redirect($menu['url']);
        }
        return FALSE;
    }

    public function actionError(\Exception $exception) {
        return $this->error($exception->getMessage());
    }

    public function beforeRender(ViewEvent $event) {
        $params = $event->params;
        if (isset($params['content'])) {
            return;
        }

        $this->view->params['breadcrumbs'] = [];
        $this->view->params['breadcrumbs'][] = ['label' => $this->name, 'url' => ["{$this->id}/"]];

        if ($this->action->id === 'save' && isset($params['model'])) {
            $model = $params['model'];
            $act = ($model->IsNewRecord ? '添加' : '编辑') . str_replace('管理', '', $this->name);
            $this->view->params['breadcrumbs'][] = $this->view->title = $act;
        } elseif ($this->action->id === 'view') {
            $title = "查看{$this->view->title}";
            $title = str_replace('管理', '', $title);
            $this->view->params['breadcrumbs'][] = $this->view->title = $title;
        } elseif ($this->action->id !== 'index') {
            if (!empty($this->view->title)) {
                $this->view->params['breadcrumbs'][] = $this->view->title;
            }
        }
    }

    public function actionLogout() {
        Yii::$app->user->logout();
        return Yii::$app->getResponse()->redirect(['/admin/auth/login']);
    }
}